/*
 * @(#)ImageByOwfsBO.java $version 2011. 10. 14
 * 
 * Copyright 2011 NHN Corp. All rights Reserved.
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.hangame.mbl.bo.feed;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.lucy.common.data.DataHandlerFactory;
import com.nhncorp.owfs.Owfs;
import com.nhncorp.owfs.OwfsException;
import com.nhncorp.owfs.OwfsFile;
import com.nhncorp.owfs.OwfsOwner;

// TODO: Auto-generated Javadoc
/**
 * The Class ImageByOwfsBO.
 *
 * @author NHN
 */
public class ImageByOwfsBO {
	
	/** The log. */
	private static Log log = LogFactory.getLog(ImageByOwfsBO.class);
	
	/** The Constant MDS_IP. */
	private static final String MDS_IP = DataHandlerFactory.getDataHandler().get("owfs/ip"); // OWFS IP			
	
	/** The Constant SERVICE_CODE. */
	private static final String SERVICE_CODE = DataHandlerFactory.getDataHandler().get("owfs/serviceCode"); // 서비스코드
	
	/** The Constant DOWNLOAD. */
//	private static final String DOWNLOAD  = DataHandlerFactory.getDataHandler().get("owfs/download"); // read
	
	/** The Constant BUF_LEN. */
	private static final int BUF_LEN = 1024 * 1024; // 버퍼사이즈
	
	/**
	 * Upload owfs file.
	 * 
	 * @param localFile the local file
	 * @param extension the extension
	 * @return the string
	 */
	public String uploadOwfsFile(File localFile, String extension) {
		
		OwfsOwner owfsOwner = null;
		FileInputStream localFileInputStream = null;
		OwfsFile owfsFile = null;
		OutputStream owfsFileOutputStream = null;
		
		String ownername = DateFormatUtils.format(new Date(), "yyyyMMdd");	// TODAY
		String fileName = ((Long)System.nanoTime()).toString() + "." + extension;
//		String userUploadFileName = DOWNLOAD + ownername + "/" + fileName;	// atch_file_url -> owner/fileName 으로 데이터셋 변경(with 양현규 협의내용)
		String userUploadFileName = ownername + "/" + fileName;

		
		try {
			// Owfs 연결
			Owfs owfs = Owfs.init(MDS_IP, SERVICE_CODE);	
			
			log.debug("##### OWFS uploadOwfsFile owner : " + ownername);
			log.debug("##### OWFS uploadOwfsFile localFile : " + localFile);

			// OwfsOwner 객체 생성
			owfsOwner = new OwfsOwner(owfs, ownername);
			// OwfsOwner 생성 or 오픈
			if (!owfsOwner.exists()) {
				owfsOwner.create();
			} else {
				owfsOwner.open();
			}

			localFileInputStream = new FileInputStream(localFile);
			
			owfsFile = new OwfsFile(owfsOwner, fileName);
			
			if (owfsFile.exists()) {	// 동일한 파일명이 존재할 경우.
				log.debug("##### OWFS file Already EXIST!!");
				return "OWFS_ERR";
			}
			owfsFile.open(true);

			owfsFileOutputStream = owfsFile.getOutputStream();

			int readLen;
			int totalSize = 0;
			byte[] buf = new byte[BUF_LEN];

			long startTime = System.currentTimeMillis();
			while ((readLen = localFileInputStream.read(buf, 0, buf.length)) >= 0) {
				owfsFileOutputStream.write(buf, 0, readLen);
				totalSize += readLen;
			}
			log.debug("##### OWFS upload totalSize : " + totalSize);
			
			long endTime = System.currentTimeMillis();
			log.debug("#### OWFS upload SUCCESS. total time: " + ((endTime - startTime) / 1000) + "second");
			
		} catch (Exception e) {
			log.error("##### OWFS uploadOwfsFile ERROR : " + e, e);
			return "OWFS_ERR";
		} finally {
			if (owfsFileOutputStream != null) {
				try {
					owfsFileOutputStream.flush();
				} catch (IOException e) {
					log.error("##### OWFS owfsFileOutputStream flush ERROR : " + e, e);
				}
				try {
					owfsFileOutputStream.close();
				} catch (IOException e) {
					log.error("##### OWFS owfsFileOutputStream close ERROR : " + e, e);
				}
			}
			if (localFileInputStream != null) {
				try {
					localFileInputStream.close();
				} catch (IOException e) {
					log.error("##### OWFS localFileInputStream close ERROR : " + e, e);
				}
			}
			if (owfsFile != null && owfsFile.isOpened()) {
				try {
					owfsFile.close();
				} catch (OwfsException e) {
					log.error("##### OWFS owfsFile close ERROR : " + e, e);
				}
			}
			if (owfsOwner != null && owfsOwner.isOpened()) {
				owfsOwner.close();
			}
		}
		return userUploadFileName;
	}

}
